import router, { resetRouter, constantRoutes } from '@/router'
import { list } from '@/api/modules/menu'
import store from '../index'
import Layout from '@/layout'

let outMemberNo = ''
let tokenKey = ''
/**
 * 获取外链数据
 * @param {*} urlAlias
 * @returns
 */
function getLinkUrl(urlAlias) {
  if (!outMemberNo) { outMemberNo = store.getters.curBusiness.id }
  if (!tokenKey) { tokenKey = store.getters.tokenKey }

  switch (urlAlias) {
    case 'ebusiness':
      return {
        link: process.env.VUE_APP_EBUSINESS,
        query: { outMemberNo }
      }
    case 'collect':
      return {
        link: process.env.VUE_APP_COLLECT,
        query: { tokenKey }
      }
    case 'financing':
      return {
        link: process.env.VUE_APP_FINANCING,
        query: { tokenKey }
      }
    default:
      return {}
  }
}

/**
 * 路由表格式化
 * @param {Array} dataRoutes
 */
function formatRoutes(routers,item) {
  // 简单检查是否是可以处理的数据
  if (!(routers instanceof Array)) {
    return false
  }
  // 处理后的容器
  return routers.map(route => {
    let children = route.children
    const redirect = route.redirect
    // 如果有子组件，递归处理
    if (children && children instanceof Array) {
      children = formatRoutes(children,item)
    }
    const fmRouter = {
      path:!route.path.includes('/')?`/${route.path}`:`${route.path}`|| '/',
      fullPath: route.path || '/',
      name: route.name,
	    hidden:route.hidden,
      children: children,
      id:route.id?route.id:"",
      parenId:route.parenId?route.parenId:item.parenId,
      meta: {
        icon: route.meta.icon?route.meta.icon:"",
        title: route.meta.title,
        id:route.id?route.id:"",
        parenId:route.parenId?route.parenId:item.id,
		    activeMenu:route.meta.activiteMenu,
        ...getLinkUrl(route.url)
      },
      redirect: redirect
    }
    if(children && children instanceof Array){
      fmRouter.component = () => import("@/layout/new.vue");
    }else{
      fmRouter.component = () => import("@/views/" + route.component + ".vue");
    }
    return fmRouter
  })
}
/**
 * 生成路由
 * @param {Array} routes
 */
function generateRoutes(routes,type=1) {
  const list = routes.map((item)=>{
   let label  = {
        path: `${item.path}`,
        id:item.id?item.id:"",
        hidden:item.hidden,
        meta:{title:item.meta&&item.meta.title?item.meta.title:'',icon:item.meta&&item.meta.icon?item.meta.icon:'',activeMenu:item.meta&&item.meta.activiteMenu?item.meta.activiteMenu:''},
        parenId:item.parenId?item.parenId:"",
        component: Layout,
        children: formatRoutes(item.children,item)
      }
    
	  return label
  })
  console.log('gfontlist',list)
  return list
}

/**
 * 生成菜单
 * @param {Array} routes
 */
function generateMenu(routes) {
  return routes
}

const state = {
  // 权限路由
  routes: [],
  // 模块儿列表
  mkallData: [],
  // 初始路径
  defaultparenId: '',
  // 菜单列表
  menuData: [],
  // 所有路由
  allRoutes: [],
  // 初始路径
  defaultPath: ''
}

const mutations = {
  SET_MKROUTES: (state, routes) => {
    let boxroute = [];
    routes.forEach((item)=>{
      if(item.meta){
        boxroute.push(item)
      }
    })
    state.defaultparenId = boxroute[0].id;
    state.mkallData = [...boxroute]
  },
  SET_PARENT: (state, id) => {
    state.defaultparenId =id;
  },
  SET_ROUTES: (state, routes) => {
    let Aroutes = [];
    routes.forEach((item)=>{
      if(item.children.length&&item.children){
        item.children.forEach((label)=>{
          label.parenId = item.id;
          Aroutes.push(label)
        })
      }
    })
    state.menuData = generateRoutes(routes,2)
    state.routes = constantRoutes.concat(routes)
  },
  UPDATE_ALL_ROUTES: (state, routes) => {
    state.allRoutes = routes
  },
  UPDATE_DEFAULT_PATH: (state, path) => {
    state.defaultPath = path
  }
}

const actions = {
  // 更新全模块儿所有功能
  updateAllmenu({ commit, state }, data) {
    return new Promise(resolve => {
      commit('SET_MKROUTES',data)
      resolve(data)
    })
  },
  // 更新路由菜单
  updateRoutes({ commit, state }, data) {
    return new Promise(resolve => {
      commit('SET_ROUTES', generateRoutes(data))
      const menu = data[0]
      if (menu) {
        if (menu.type === 2 || menu.type === 3) {
          commit('UPDATE_DEFAULT_PATH', menu.path)
        } else if (menu.routes && menu.routes[0].component && (menu.routes[0].type === 2  || menu.type === 3)) {
          commit('UPDATE_DEFAULT_PATH', menu.routes[0].path)
        }
      }
	  const routers = store.getters.permission_routes;
	  routers.forEach((route)=>{
	  	  router.addRoute(route);
	  })
      resolve(generateRoutes(data))
    })
  },
  // 更新主要模块儿
  updateParent({ commit, state }, id) {
      return new Promise(resolve => {
        commit('SET_PARENT', id)
        resolve(id)
      })
  },
  // 初始化更新全部菜单列表
  updateAllRoutes({ commit }, param) {
    return new Promise((resolve, reject) => {
      list(param).then(response => {
        const { body } = response
        commit('UPDATE_ALL_ROUTES', body)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 初始化首页路径
  updateDefaultPath({ commit }, path) {
    return new Promise(resolve => {
      commit('UPDATE_DEFAULT_PATH', path)
      resolve(path)
    })
  },
  // 根据角色id更新菜单列表
  updateAllRoutesById({ commit }, roleId) {
    return new Promise((resolve, reject) => {
      listById(roleId).then(response => {
        const { body } = response
        resetRouter()
        commit('SET_ROUTES', generateRoutes(body))
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
